<template>
  <div>
    <nut-config-provider :theme-vars="{
      navbarBoxShadow: 'none',
      navbarBackground: '#f8f8f8'
    }">
      <nut-navbar left-show fixed :safe-area-inset-top="true" background="#f8f8f8">
        <template #content>
          <div v-if="orderInfo" text-30rpx font-bold color-black>
            {{ orderInfo.orderStatusValue }}
          </div>
        </template>
      </nut-navbar>
    </nut-config-provider>
    <div v-if="isShow" px-16rpx pb-200rpx>
      <!-- 快递信息 -->
      <div card mb-24rpx v-if="orderPackage.length">
        <div class="order-cell">
          <div class="order-cell_label" style="color:#000">当前订单有<span text-26rpx font-bold>{{ orderPackage.length
              }}</span>个快递包裹</div>
          <div class="order-cell_value" @click="parcel()">点击此处查看</div>
        </div>
      </div>
      <div
        v-if="(orderInfo.order.orderType === 'VIRTUAL' || orderInfo.order.deliveryMethod === 'SELF_PICK_UP') && orderInfo.order.verificationCode"
        mb-24rpx card p-32rpx text-center text-neutral-500>核验码：<span text-red-500
          font-semibold>{{ orderInfo.order.verificationCode }}</span></div>
      <!-- 循环商品 -->
      <div mb-24rpx card p-32rpx>
        <div text-28rpx font-bold flex flex-a-c mb-24rpx
          @click="$navigateTo('/pages/goods/store/detail?id=' + orderInfo.order.storeId)">
          {{ orderInfo.order.storeName }} <nut-icon size="12" name="rect-right"></nut-icon>
        </div>
        <div my-10rpx v-for="(item, index) in orderInfo.orderItems" :key="index">
          <order :res="item">
            <template #body>
              <div mt-24rpx flex justify-end>
                <nut-button size="small"
                  v-if="item.afterSaleStatus && (item.afterSaleStatus.includes('NOT_APPLIED') || item.afterSaleStatus.includes('PART_AFTER_SALE'))"
                  @tap.stop="refund(item)">退款/售后</nut-button>
              </div>
            </template>
          </order>
        </div>
      </div>
      <!-- 订单信息 -->
      <div mb-24rpx card>
        <!-- <div class="order-cell"
          v-if="(orderInfo.order.orderType === 'VIRTUAL' || orderInfo.order.deliveryMethod === 'SELF_PICK_UP') && orderInfo.order.verificationCode">
          <div class="order-cell_label">劵码：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{ orderInfo.order.verificationCode }}</div>
        </div> -->

        <div class="order-cell"
          v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'SELF_PICK_UP'">
          <div class="order-cell_label">自提点地址：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{ orderInfo.order.storeAddressPath }}</div>
        </div>

        <div class="order-cell"
          v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'SELF_PICK_UP'">
          <div class="order-cell_label">联系方式：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{ orderInfo.order.storeAddressMobile }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">实付款：</div>
          <div class="order-cell_value" text-main-color font-bold text-26rpx>{{
            unitPrice(orderInfo.order.priceDetailDTO.flowPrice, '￥') }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">商品总价：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{
            unitPrice(orderInfo.order.goodsPrice, '￥') }}</div>
        </div>
        <div class="order-cell" v-if="orderInfo.order.freightPrice">
          <div class="order-cell_label">运费：</div>
          <div class="order-cell_value" font-bold text-26rpx>+{{
            unitPrice(orderInfo.order.priceDetailDTO.freightPrice, '￥') }}</div>
        </div>
        <div class="order-cell" v-if="orderInfo.order.giftPoint">
          <div class="order-cell_label">赠送积分：</div>
          <div class="order-cell_value" font-bold text-26rpx>+{{
            unitPrice(orderInfo.order.priceDetailDTO.giftPoint, '') }}</div>
        </div>
        <div class="order-cell" v-if="orderInfo.order.priceDetailDTO?.payPoint">
          <div class="order-cell_label">消费积分：</div>
          <div class="order-cell_value" font-bold text-26rpx>-{{ orderInfo.order.priceDetailDTO.payPoint }}积分</div>
        </div>
        <div class="order-cell" v-if="orderInfo.order.priceDetailDTO">
          <div class="order-cell_label">优惠券：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{
            unitPrice(orderInfo.order.priceDetailDTO.couponPrice, '￥') }}</div>
        </div>
        <div class="order-cell" v-if="orderInfo.order.priceDetailDTO">
          <div class="order-cell_label">活动优惠：</div>
          <div class="order-cell_value" font-bold text-26rpx>{{
            unitPrice(eventDiscountPrice, '￥') }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">订单编号：</div>
          <div class="order-cell_value">{{ orderInfo.order.sn }}
            <copy :content="orderInfo.order.sn" />
          </div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">订单备注：</div>
          <div class="order-cell_value">{{ orderInfo.order.remark || '暂无备注' }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">订单类型：</div>
          <div class="order-cell_value">
            <span v-if="orderInfo.order.orderType === 'VIRTUAL'">虚拟订单</span>
            <span v-if="orderInfo.order.orderType === 'NORMAL'">普通订单</span>
          </div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">支付时间：</div>
          <div class="order-cell_value">{{ orderInfo.order.paymentTime || '暂无' }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">下单时间：</div>
          <div class="order-cell_value">{{ orderInfo.order.createTime || '' }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">支付状态：</div>
          <div class="order-cell_value"> {{
            orderInfo.order.payStatus == "UNPAID" ? "未付款" : orderInfo.order.payStatus == "PAID" ? "已付款" : ""
          }}</div>
        </div>
        <div class="order-cell">
          <div class="order-cell_label">支付方式：</div>
          <div class="order-cell_value"> {{
            orderInfo.paymentMethodValue || '暂无'
          }}</div>
        </div>

        <div class="order-cell"
          v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod !== 'SELF_PICK_UP'">
          <div class="order-cell_label">收货信息：</div>
          <div class="order-cell_value">
            <div>
              姓名：{{ orderInfo.order.consigneeName }}
            </div>
            <div>
              手机号：{{ orderInfo.order.consigneeMobile }}
            </div>
          </div>
        </div>
        <div class="order-cell"
          v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod !== 'SELF_PICK_UP'">
          <div class="order-cell_label">收货地址：</div>
          <div class="order-cell_value">{{ orderInfo.order.consigneeAddressPath || '' }}{{
            orderInfo.order.consigneeDetail
            || '' }}
          </div>
        </div>
      </div>
      <!-- 发票信息 -->
      <div card v-if="orderInfo.order.payStatus == 'PAID'">
        <div class="order-cell">
          <div class="order-cell_label">发票信息：</div>
          <div class="order-cell_value">
            <span v-if="!orderInfo.order.needReceipt">不开发票</span>
            <span v-else>请联系客服</span>
            <!-- <span flex flex-a-c v-else @click="previewReceipt(orderInfo.receipt)">
              查看发票
              <nut-icon size="12" name="rect-right"></nut-icon>
            </span> -->
          </div>
        </div>
      </div>
    </div>

    <div class="tab-bar" flex flex-a-c justify-end
         v-if="(orderInfo.allowOperationVO && orderInfo.allowOperationVO.cancel == true)
               || (orderInfo?.order?.orderStatus == 'DELIVERED')
               || (orderInfo.allowOperationVO && orderInfo.allowOperationVO.pay)
               || (orderInfo?.order?.orderStatus != 'UNPAID' && orderInfo?.order?.orderPromotionType === 'PINTUAN')">
      <div flex flex-a-c gap-12rpx px-32rpx>
        <nut-button v-if="orderInfo.allowOperationVO && orderInfo.allowOperationVO.cancel == true"
          @click="cancelRef.show = true">取消订单</nut-button>
        <nut-button type="primary" @click="showDeliver = true"
          v-if="orderInfo?.order?.orderStatus == 'DELIVERED'">确认收货</nut-button>
        <nut-button @click="pay" type="primary"
          v-if="orderInfo.allowOperationVO && orderInfo.allowOperationVO.pay">立即付款</nut-button>
        <nut-button
          @click="$navigateTo('/pages/mine/order/share?sn=' + orderInfo.order.sn + '&skuId=' + orderInfo.orderItems[0].skuId + '&goodsId=' + orderInfo.orderItems[0].goodsId)"
          type="primary"
          v-if="orderInfo?.order?.orderStatus != 'UNPAID' && orderInfo?.order?.orderPromotionType === 'PINTUAN'">拼团详情</nut-button>
      </div>
    </div>

    <!-- 确认收货 -->
    <nut-dialog title="提示" content="是否确认收货？" v-model:visible="showDeliver" @ok="handleSubmitDeliver" />
    <!-- 取消订单 -->
    <cancelModule :loading="cancelLoading" @click="handleSubmitCancel" ref="cancelRef" />
    <!-- 加载 -->
    <nut-toast ref="toastRef" />
  </div>
</template>

<script setup lang="ts">
import { getOrderDetail, getPackage } from "@/api/order";
import order from '@/components/basic-template/order.vue';
import copy from '@/components/copy/index.vue';
import cancelModule from '@/pages/mine/order/cancel.vue';
import { confirmCancelOrder, confirmDeliver } from '@/pages/mine/order/operation';
import { unitPrice } from '@/utils/filters';
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';

const routerVal = ref<any>({}) //路由信息
const isShow = ref(false) //是否展示页面
const orderPackage = ref<any>([]) //包裹
const orderInfo = ref<any>({}) // 订单详情
const eventDiscountPrice = ref<any>(0); // 活动优惠金额
const cancelLoading = ref<boolean>(false)
const cancelRef = ref<any>(null)
const showDeliver = ref<boolean>(false)
const toastRef = ref<ToastInst>()
// 点击取消订单
async function handleSubmitCancel(reason: string) {
  cancelLoading.value = true

  const operation = await confirmCancelOrder(routerVal.value.sn, reason)
  cancelLoading.value = false
  cancelRef.value.show = false
  if (operation) {
    init()
  }
}

// 快递详情
function parcel() {
  uni.navigateTo({
    url: `/pages/mine/order/deliver?sn=${routerVal.value.sn}`
  })
}

async function init() {
  uni.stopPullDownRefresh();
  getOrderInfo()
  getOrderPackage()

}

// 订单详情
async function getOrderInfo() {
  const res = await getOrderDetail(routerVal.value.sn)
  if (res.data.success) {
    isShow.value = true
    orderInfo.value = res.data.result;
    // 计算活动优惠金额
    if (res.data.result.order.priceDetailDTO && res.data.result.order.priceDetailDTO.discountPriceDetail && res.data.result.order.priceDetailDTO.discountPriceDetail.length) {
      const numbers = res.data.result.order.priceDetailDTO.discountPriceDetail.map((item: any) => item.discountPrice);
      // const sum = eval(numbers.join('+'));
      const sum = numbers.reduce((accumulator: any, currentValue: any) => accumulator + currentValue, 0);
      eventDiscountPrice.value = sum;
    } else {
      eventDiscountPrice.value = 0;
    }
  }
}
// 查看包裹
async function getOrderPackage() {
  const res = await getPackage(routerVal.value.sn)
  if (res.data.success) {
    orderPackage.value = res.data.result
  }
}

// 退款售后
async function refund(item: any) {
  uni.navigateTo({
    url: `/pages/mine/aftersale/list?orderSn=${item.orderSn}`,
  });
}

// 去支付
function pay() {
  uni.navigateTo({
    url: `/pages/mine/payment/payOrder?trade_sn=${orderInfo.value.order.tradeSn}`
  })
}

// 查看发票
function previewReceipt(val: any) {
  uni.navigateTo({
    url: "/pages/mine/order/invoiceDetail?id=" + val.id,
  });
}

// 确认收货
async function handleSubmitDeliver() {
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const operation = await confirmDeliver(routerVal.value.sn)
  toastRef.value?.hideToast();
  if (operation) {
    init();
  }
}

onPullDownRefresh(() => {
  init()
})

onLoad((options) => {
  routerVal.value = options
  init()
})
</script>

<style scoped lang="scss">
.order-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;

  font-size: 24rpx;

  &_label {
    color: #999;
    font-size: 24rpx;
    min-width: 150rpx;
  }

  &_value {
    text-align: right;

  }
}

.tab-bar {
  background: #fff;
  height: 100rpx;
  position: fixed;
  bottom: 0;
  width: 100vw;
}
</style>
